package com.yonyou.cyxdms.sysAuth.service.service.Login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoleilu.hutool.date.DateTime;
import com.yonyou.cloud.http.plus.domain.MessEvent;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cms.channel.client.service.message.CmsChannelCommonService;
import com.yonyou.cms.channel.client.vo.message.DealerAttachVO;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.service.http.HttpRequestService;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.bean.dto.http.RestServiceRequestDto;
import com.yonyou.cyx.function.bean.dto.http.RestServiceResponseDto;
import com.yonyou.cyx.function.exception.DMSAuthException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.domains.vo.CodeVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.RegionVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonCodeService;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonRegionService;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.ExtraImDto;
import com.yonyou.cyxdms.sysAuth.service.dto.*;
import com.yonyou.cyxdms.sysAuth.service.dto.dealer.MsgRecordPO;
import com.yonyou.cyxdms.sysAuth.service.dto.notification.TextNotifyDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.UserPermissionActionListDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.feign.ImService;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.EmpService;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;
import com.yonyou.cyxdms.sysAuth.service.service.broker.BrokerService;
import com.yonyou.cyxdms.sysAuth.service.service.jwt.JwtService;
import com.yonyou.cyxdms.sysAuth.service.service.log.OperateLogService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleService;
import com.yonyou.cyxdms.sysAuth.service.utill.*;
import com.yonyou.cyxdms.sysAuth.service.vo.role.RolePageVO;
import com.yonyou.cyxdms.sysAuth.service.vo.user.BindingPhoneVO;
import com.yonyou.cyxdms.sysAuth.service.vo.weChat.SmsWxVo;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.*;
import com.yonyou.cyxdms.sysmanage.client.service.login.PushServices;
import cz.mallat.uasparser.UserAgentInfo;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.interfaces.RSAPrivateKey;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
@Service
public class UserLoginServiceImpl implements UserLoginService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(UserLoginServiceImpl.class);
    @Autowired
    public UserLoginMapper userLoginMapper;

    @Autowired
    private RedisClient redisClient;
    @Autowired
    public RedissonClient redissonClient;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    private CmsChannelCommonService cmsChannelCommonService;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private SystemParamMapper systemParamMapper;

    @Autowired
    private BaseCommonRegionService baseCommonRegionService;

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsLogMapper smsLogMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    MsgRecordMapper msgRecordMapper;

    @Autowired
    HttpRequestService requestService;

    @Autowired
    private PushServices pushService;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    OperateLogService operateLogService;
    @Autowired
    EmpService empService;

    @Autowired
    JwtService jwtService;

    @Autowired
    BaseCommonCodeService baseCommonCodeService;

    @Autowired
    private RoleService roleService;

    @Autowired
    HttpRequestService httpRequestService;

    @Value("${push.appId}")
    private String pushAppId;

    @Value("${sms.appId}")
    private String smsAppId;

    @Value("${sms.templateId-1}")
    private String smsTemplateId1;



    @Value("${cyxEmployeeUrl}")
    private String cyxEmployeeUrl;

    @Value("${tm.url}")
    private String tmUrl;

    @Value("${zht.service.addMsg.url}")
    private String addMsgUrl;

    @Value("${zht.service.jwtLogin.url}")
    private String jwtLoginUrl;

    private String signName = "北汽营销";

    @Value("${aliyun.smsSend.minute}")
    private String minute;

    @Value("${aliyun.smsSend.templateCode}")
    private String templateCode;

    @Value("${aliyun.smsSend.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.smsSend.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    HttpRequestService httpService;

    @Autowired
    ImService imService;

    @Autowired
    public BrokerService brokerService;

    @Autowired
    UserService userService;
    @Autowired
    IRemoteInvoke iRemoteInvoke;

    @Autowired
    private WechatScanLoginService wechatScanLoginService;


    @Autowired
    private TtUserLoginMapper ttUserLoginMapper;

    @Autowired
    private SystemParamService systemParamService;

    /**
     * 验证用户名密码是否正确
     *
     * @param userLoginDto
     * @return Map
     * @author maxingjian
     * @date 2017年6月23日
     */
    @Override
    public Map<String, Object> login(UserLoginDTO userLoginDto, String userAgent, Integer logWay) throws Exception {
        logger.info("userName:" + userLoginDto.getUsername());
        userLoginDto.setAppId("RL");
        List<Map> result = new ArrayList<>();
        Long isexist = 0L;
        if (StringUtils.isNullOrEmpty(userLoginDto.getLoginType())) {
            userLoginDto.setLoginType(1);
        }
        if (userLoginDto.getLoginType() != 3) {
            isexist = userLoginMapper.existAppId(userLoginDto.getAppId());
            if (isexist == 0) {
                logger.info("站点不存在！");
                throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, SysAuthCommonConstants.EXISTS_APPID);
            }
        }

        if (!StringUtils.isNullOrEmpty(userLoginDto.getUsername())) {

            List<UserPO> userPOs = userLoginMapper.findUser(userLoginDto.getAppId(), userLoginDto.getUsername());
            if (userPOs.size() > 0) {
                UserPO userPO = userPOs.get(0);
                if (userPO.getFailureNum() > 9) {
                    if (userPO.getFailureNum() > 9) {
                        HashMap<String, String> map = new HashMap<>();
                        Date now = Calendar.getInstance().getTime();
                        double nowtime = now.getTime();
                        double logintime = userPO.getLoginLastTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                        double timeDifference = Math.floor(nowtime / 160000 - logintime / 160000);
                        double timeDifference2 = Math.floor(30 - timeDifference);
                        NumberFormat nf = NumberFormat.getInstance();
                        String timeDifference3 = nf.format(timeDifference2);
                        if (timeDifference < 30) {
                            map.put("msg", "当前账户被锁定，请" + timeDifference3 + "分钟后重试！");
                            //throw new ServiceBizException(JSONUtil.objectToJson(map));
                            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, JSONUtil.objectToJson(map));
                        } else {
                            // 5分钟时间到，解锁
                            setEmpPo6(userPO.getUserId(), userPO.getAppId());
                        }
                    } else {
                        userPO.setLoginLastTime(LocalDateTime.now());
                        userMapper.updateById(userPO);
                    }
                }

            }

            isexist = userLoginMapper.existUser(userLoginDto.getAppId(), userLoginDto.getUsername());
            if (isexist == 0) {
                logger.info("登录账号无效，不能登录！");
                throw new DMSAuthException(990, SysAuthCommonConstants.USER_INVALID);
            }
        }


        if (StringUtils.isNullOrEmpty(userLoginDto.getLoginType()) || userLoginDto.getLoginType() == 1) {
            if (StringUtils.isNullOrEmpty(userLoginDto.getUsername())) {
                logger.info("用户名username为空！");
                HashMap<String, Object> map = MapUtils.newHashMap();
                map.put("msg", SysAuthCommonConstants.CAN_NOT_LOGIN);
                throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, JSONUtil.objectToJson(map));
            }
            result = getUser(userLoginDto.getAppId(), userLoginDto.getUsername(), null);

        } else if (userLoginDto.getLoginType() == 2) {
            if (StringUtils.isNullOrEmpty(userLoginDto.getPhone())) {
                logger.info("用户名MobilePhone为空！");
                throw new DMSAuthException(990, SysAuthCommonConstants.PHONE_NOT_BINDING);
            }
            result = getUser(userLoginDto.getAppId(), null, userLoginDto.getPhone());
            if (CommonUtils.isNullOrEmpty(result)) {
                logger.info("查询用户为空！");
                throw new DMSAuthException(990, SysAuthCommonConstants.PHONE_NOT_BINDING);
            }
        } else if (userLoginDto.getLoginType() == 3) {
            result = userLoginMapper.getUserByOpenId(userLoginDto.getAppId(), userLoginDto.getOpenId());
            if (CommonUtils.isNullOrEmpty(result)) {
                logger.info("根据openId查询的用户为空！");
                HashMap<String, Object> map = MapUtils.newHashMap();
                //map.put("msg", SysAuthCommonConstants.CAN_NOT_LOGIN);
                throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, SysAuthCommonConstants.CAN_NOT_LOGIN);
            }
        }

        if (CommonUtils.isNullOrEmpty(result)) {
            logger.info("查询用户为空！");
            throw new DMSAuthException(SysAuthCommonConstants.CAN_NOT_LOGIN);
        }

        String userType = "1";
        String ownerCode = null;
        String groupCode = "0";

        //获取登录用户类型
        try {
            logger.info("userType:" + userLoginDto.getLoginType());
            if (!StringUtils.isNullOrEmpty(result.get(0).get("companyId"))) {
                ownerCode = result.get(0).get("companyId").toString();
            }
            logger.info("companyId:" + ownerCode);
            logger.info("groupCode:" + userLoginDto.getGroupCode());
        } catch (Exception e) {
            throw e;
        } finally {
        }
        Map loginUser = new HashMap();
        if ("1".equals(userType)) {
            try {
                String falseFlag = "";
                //pc迁移 2019.7.8 start
                Map<String, String> loginMap = null;
                if (StringUtils.isNullOrEmpty(userLoginDto.getLoginType()) || userLoginDto.getLoginType() == 1) {
                    //验证用户信息，是否通过

                    loginMap = userlogCheck(userLoginDto.getAppId(), result.get(0).get("userCode").toString(), userLoginDto.getPassword(), userLoginDto.getGroupCode(), userLoginDto.getVerificationCode(), userLoginDto.getDeviceId(), userLoginDto.getRegId());
                    falseFlag = loginMap.get("isfalse");
                    if ("true".equals(falseFlag)) {
                        if (result.size() == 0) {
                            throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "账号无效");
                        } else if (result.size() > 1) {
                            throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "当前账号绑定人员过多，不能登录，请联系管理员");
                        }
                        Map map = result.get(0);
                        SmsWxVo smsWx = getSmsWx(userLoginDto.getAppId());
                        if (logWay.equals(SysAuthDictCodeConstants.STATUS_IS_YES)) {
                            if (smsWx.getSmsType() == ManageDictCodeConstants.STATUS_IS_YES) {
                                Object phone = map.get("phone");
                                if (phone == null) {
                                    throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "账号未绑定手机号，请先绑定");
                                }
                                String mphone = (String) phone;
                                if (StringUtils.isNullOrEmpty(mphone)) {
                                    throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "账号未绑定手机号，请先绑定");
                                }
                            }
                        }

                    }

                } else if (userLoginDto.getLoginType() == 2) {
                    //
                    falseFlag = verifyCheckCode(userLoginDto.getAppId(), result.get(0).get("userCode").toString(), userLoginDto.getPhone(), userLoginDto.getCheckCode(), userLoginDto.getRegId());
                } else if (userLoginDto.getLoginType() == 3) {
                    EmpPo empInfoByOpenId = empService.getEmpInfoByOpenId(userLoginDto.getOpenId(), userLoginDto.getAppId());
                    if (empInfoByOpenId == null) {
                        falseFlag = "flase";
                        SmsWxVo smsWx = getSmsWx(userLoginDto.getAppId());
                        if (smsWx.getSmsType() == ManageDictCodeConstants.STATUS_IS_NOT) {
                            throw new DMSAuthException(993, "微信未绑定，且无短信功能");
                        }
                    } else {
                        falseFlag = "true";
                    }

                }
                logger.info("APPID:" + userLoginDto.getAppId());
                logger.info("userCode:" + result.get(0).get("userCode").toString());
                logger.info("falseFlag:" + falseFlag);
                logger.info("userType:" + userType);
                loginUser = getLoginUser(userLoginDto.getAppId(), result.get(0).get("userCode").toString(), falseFlag, userType);
                //2019.7.8 pc迁移
                loginUser.put("userType", userType);
                loginUser.put("groupCode", groupCode);
                //pc迁移 2019.7.8 start
                if (!ObjectUtils.isEmpty(loginMap)) {
                    loginUser.put("isFirstLogin", loginMap.get("isFirstLogin"));
                    loginUser.put("employeeId", loginMap.get("employeeId"));
                    loginUser.put("orgCode", loginMap.get("orgCode"));
                    loginUser.put("userCode", loginMap.get("userCode"));
                    loginUser.put("userStatus", loginMap.get("userStatus"));

                    try {
                        TtUserLoginPO ttUserLoginPO = new TtUserLoginPO();
                        ttUserLoginPO.setAppId(userLoginDto.getAppId());
                        ttUserLoginPO.setCompanyId((Long) loginUser.get("companyId"));
                        ttUserLoginPO.setOperateDate(LocalDateTime.now());
                        ttUserLoginPO.setOperator((Long) loginUser.get("userId"));
                        ttUserLoginPO.setLoginWay(logWay);
                        UserAgentInfo parse = UserAgentUtils.uasParser.parse(userAgent);
                        ttUserLoginPO.setUserAgent(userAgent);
                        ttUserLoginPO.setDeviceName(parse.getUaFamily());
                        ttUserLoginPO.setDeviceVersion(parse.getBrowserVersionInfo());
                        ttUserLoginPO.setOsName(parse.getOsName());
                        ttUserLoginPO.setBrowerType(parse.getType());
                        ttUserLoginPO.setLastOperateDate(LocalDateTime.now());
                        ttUserLoginPO.setOrgId(-1L);
                        ttUserLoginMapper.insert(ttUserLoginPO);
                        loginUser.put("userLoginId", ttUserLoginPO.getUserLoginId());
                    } catch (IOException e) {
                        logger.error("登录日志记录失败", e);
                    }
                }
            } catch (Exception e) {
                throw e;
            }
        }

        return loginUser;
    }


    /**
     * 获取用户的权限数据
     *
     * @return Map
     * @author maxingjian
     * @date 2017年6月23日
     */
    @Override
    public Map<String, Object> appUserData() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map userData = new HashMap();
        List<Map> userDetailList = userLoginMapper.getUserDetails(loginInfoDto.getAppId(), loginInfoDto.getEmpId().toString());
        getData(userData, userDetailList);

        List<UserRoleDTO> userRolesList = userLoginMapper.findEmpPotenialRoles(loginInfoDto.getUserId().toString());
        userData.put("roles", userRolesList);
        return userData;
    }

    private void getData(Map userData, List<Map> userDetailList) {
        if (userDetailList.size() > 0) {
            userData.put("detail", userDetailList.get(0));
            userData.put("existPhone", "0");
            if (StringUtils.isNullOrEmpty(userDetailList.get(0).get("mobilePhone")))// && StringUtils.isNullOrEmpty(userDetailList.get(0).get("isReplace")))
            {
                //该用户不存在绑定手机号，需要绑定手机号码
                userData.remove("existPhone");
                userData.put("existPhone", "1");
            }
//            if (StringUtils.isNullOrEmpty(userDetailList.get(0).get("mobilePhone")) && !StringUtils.isNullOrEmpty(userDetailList.get(0).get("isReplace"))) {
//                //该用户不存在绑定手机号，且被其他账号绑定
//                userData.remove("existPhone");
//                userData.put("existPhone", "2");
//            }
            if (StringUtils.isEquals(userDetailList.get(0).get("isGroup"), "YES")) {
                String organizationIdArray = userDetailList.get(0).get("organzationIdArray").toString();
                String[] organizationIdArray1 = organizationIdArray.split(",");

                if (organizationIdArray1.length > 0) {
                    List<Map> dealerOrg = userLoginMapper.getDealerOrg();
                    List<Map> departmentList = new ArrayList<>();
                    for (int i = 0; i < organizationIdArray1.length; i++) {
                        for (int j = 0; j < dealerOrg.size(); j++) {
                            Map departmentMap = new HashMap();
                            if (dealerOrg.get(j).get("orgId").toString().equals(organizationIdArray1[i])) {
                                departmentMap.put("orgId", dealerOrg.get(j).get("orgId"));
                                departmentMap.put("orgName", dealerOrg.get(j).get("orgName"));
                                departmentList.add(departmentMap);
                            }
                        }
                    }
                    userData.put("department", departmentList);
                }
            }
            Integer needUpdate = 10041002;
            try {
                needUpdate = systemParamService.needUpdate();
            } catch (Exception e) {
                logger.error("数据库可能缺少字段", e);
            }
            userData.put("needUpdate", needUpdate);
        }
    }



    /**
     * 获取用户的权限数据合并全新用
     *
     * @return Map
     * @author maxingjian
     * @date 2017年9月21日
     */
    @Override
    public Map<String, Object> appUserDataNew() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map userData = new HashMap();
        List<Map> userDetailList = userLoginMapper.getUserDetails(loginInfoDto.getAppId(), loginInfoDto.getEmpId().toString());
        getData(userData, userDetailList);

        List<CodeVO> listcode = baseCommonCodeService.getCodeListByType(String.valueOf(ManageDictCodeConstants.CHECKEDLIST1));
        List<UserRoleDTO> userRolesList = userLoginMapper.findEmpPotenialRoles(loginInfoDto.getUserId().toString());
        for (UserRoleDTO dto : userRolesList) {
            for (CodeVO vo : listcode) {
                if (dto.getRole().equals(vo.getCodeId().toString())) {
                    dto.setPositionName(vo.getCodeCnDesc());
                }
            }
        }
        List<Map<String, Object>> list = userLoginMapper.findEmpOrg(loginInfoDto.getUserId().toString());

        String positionCode;
        String orgIdStr;

        //10061011	前台接待
        //10061012	网销顾问
        //10061013	展厅经理
        //10061015	展厅顾问
        //10061019	网销经理

        //【展厅顾问+网销顾问+前台接待】，登录后，以展厅顾问的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            if (positionCode.contains("10061011") && positionCode.contains("10061012") && positionCode.contains("10061015")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr)) {
                        if (userRolesList.get(i).getRole().equals("10061015")) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061011,10061012");
                            String str = null;
                            for (CodeVO vo : listcode) {
                                if ("10061011".equals(vo.getCodeId().toString()) || "10061012".equals(vo.getCodeId().toString())) {
                                    if (str == null) {
                                        str = vo.getCodeCnDesc();
                                    } else {
                                        str = str + "|" + vo.getCodeCnDesc();
                                    }
                                }
                            }
                            userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + str + ")");
                        } else if (userRolesList.get(i).getRole().equals("10061011") || userRolesList.get(i).getRole().equals("10061012")) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061011", "");
                positionCode = positionCode.replace("10061012", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        //【展厅顾问+网销顾问】，登录后，以展厅顾问的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            if (positionCode.contains("10061012") && positionCode.contains("10061015")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr) &&
                            positionCode.contains(userRolesList.get(i).getRole())) {
                        if (userRolesList.get(i).getRole().equals("10061015")) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061012");
                            for (CodeVO vo : listcode) {
                                if ("10061012".equals(vo.getCodeId().toString())) {
                                    userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + vo.getCodeCnDesc() + ")");
                                }
                            }
                        } else if (userRolesList.get(i).getRole().equals("10061012")) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061012", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        //【展厅顾问+前台接待】，登录后，以展厅顾问的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            if (positionCode.contains("10061011") && positionCode.contains("10061015")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr) &&
                            positionCode.contains(userRolesList.get(i).getRole())) {
                        if (userRolesList.get(i).getRole().equals("10061015")) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061011");
                            for (CodeVO vo : listcode) {
                                if ("10061011".equals(vo.getCodeId().toString())) {
                                    userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + vo.getCodeCnDesc() + ")");
                                }
                            }
                        } else if (userRolesList.get(i).getRole().equals("10061011")) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061011", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        //【展厅经理+网销经理】，登录后，以展厅经理的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            if (positionCode.contains("10061013") && positionCode.contains("10061019")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr) &&
                            positionCode.contains(userRolesList.get(i).getRole())) {
                        if (userRolesList.get(i).getRole().equals("10061013")) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061019");
                            for (CodeVO vo : listcode) {
                                if ("10061019".equals(vo.getCodeId().toString())) {
                                    userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + vo.getCodeCnDesc() + ")");
                                }
                            }
                        } else if (userRolesList.get(i).getRole().equals("10061019")) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061019", "");
                list.get(x).put("positionCode", positionCode);
            }
        }

        userData.put("roles", userRolesList);
        return userData;
    }
    /**
     * 获取用户的权限数据合并全新用
     *
     * @return Map
     * @author maxingjian
     * @date 2017年9月21日
     */
    @Override
    public Map<String, Object> appBjUserDataNew() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map userData = new HashMap();
        List<Map> userDetailList = userLoginMapper.getUserDetails(loginInfoDto.getAppId(), loginInfoDto.getEmpId().toString());
        getData(userData, userDetailList);
        List<CodeVO> listcode = baseCommonCodeService.getCodeListByType(String.valueOf(ManageDictCodeConstants.CHECKEDLIST1));
        Map<String, Object> queryCondition = new HashMap<>() ;
        queryCondition.put("dataType",loginInfoDto.getDataType());
        queryCondition.put("appId",loginInfoDto.getAppId());
        List<RolePageVO> releCode = roleMapper.getUserRoleName(null,queryCondition);
//        Map<String,String> releCodeMap = releCode.stream().collect(Collectors.toMap(RolePageVO::getRoleCode, RolePageVO::getCodeCnDesc));

        //        List<UserRoleDTO> userRolesList = userLoginMapper.findEmpPotenialRoles(loginInfoDto.getUserId().toString());
        List<UserRoleDTO> userRolesList = this.roleDetailc();
        for (UserRoleDTO dto : userRolesList) {
            for (CodeVO vo : listcode) {
                if (vo.getCodeId().toString().equals(dto.getRole())) {
                    dto.setPositionName(vo.getCodeCnDesc());
//                    dto.setRoleName(vo.getCodeCnDesc());
                }
            }
//            if(StringUtils.isNullOrEmpty(dto.getRoleName())){
//                if(StringUtils.isNullOrEmpty(releCodeMap.get(dto.getRole()))){
//
//                }
//            }
        }
        List<Map<String, Object>> list = userLoginMapper.findEmpOrg(loginInfoDto.getUserId().toString());

        String positionCode;
        String orgIdStr;

        //10061011	前台接待
        //10061012	网销顾问
        //10061013	展厅经理
        //10061015	展厅顾问
        //10061019	网销经理
//        String isContains =


        //【展厅顾问+网销顾问+前台接待】，登录后，以展厅顾问的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            String role = null;
            if (positionCode.contains("10061011") && positionCode.contains("10061012") && positionCode.contains("10061015")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    role = userRolesList.get(i).getRole();
                    if(StringUtils.isNullOrEmpty(role)){
                        role = userRolesList.get(i).getRoleCode();
                    }
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr)) {
                        if ("10061015".equals(role)) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061011,10061012");
                            String str = null;
                            for (CodeVO vo : listcode) {
                                if ("10061011".equals(vo.getCodeId().toString()) || "10061012".equals(vo.getCodeId().toString())) {
                                    if (str == null) {
                                        str = vo.getCodeCnDesc();
                                    } else {
                                        str = str + "|" + vo.getCodeCnDesc();
                                    }
                                }
                            }
                            userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + str + ")");
                        } else if ("10061011".equals(userRolesList.get(i).getRole()) || "10061012".equals(userRolesList.get(i).getRole())) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061011", "");
                positionCode = positionCode.replace("10061012", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        //【展厅顾问+网销顾问】，登录后，以展厅顾问的角色进入；
        for (int x = 0; x < list.size(); x++) {
            String role = null;
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            if (positionCode.contains("10061012") && positionCode.contains("10061015")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    role = userRolesList.get(i).getRole();
                    if(StringUtils.isNullOrEmpty(role)){
                        role = "";
                    }
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr) &&
                            positionCode.contains(role)) {
                        if ("10061015".equals(userRolesList.get(i).getRole())) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061012");
                            for (CodeVO vo : listcode) {
                                if ("10061012".equals(vo.getCodeId().toString())) {
                                    userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + vo.getCodeCnDesc() + ")");
                                }
                            }
                        } else if ("10061012".equals(userRolesList.get(i).getRole())) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061012", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        //【展厅顾问+前台接待】，登录后，以展厅顾问的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            String role = null;
            if (positionCode.contains("10061011") && positionCode.contains("10061015")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    role = userRolesList.get(i).getRole();
                    if(StringUtils.isNullOrEmpty(role)){
                        role = "";
                    }
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr) &&
                            positionCode.contains(role)) {
                        if ("10061015".equals(userRolesList.get(i).getRole())) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061011");
                            for (CodeVO vo : listcode) {
                                if ("10061011".equals(vo.getCodeId().toString())) {
                                    userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + vo.getCodeCnDesc() + ")");
                                }
                            }
                        } else if ("10061011".equals(userRolesList.get(i).getRole())) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061011", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        //【展厅经理+网销经理】，登录后，以展厅经理的角色进入；
        for (int x = 0; x < list.size(); x++) {
            positionCode = list.get(x).get("positionCode").toString();
            orgIdStr = list.get(x).get("orgId").toString();
            String role = null;
            if (positionCode.contains("10061013") && positionCode.contains("10061019")) {
                for (int i = 0; i < userRolesList.size(); i++) {
                    role = userRolesList.get(i).getRole();
                    if(StringUtils.isNullOrEmpty(role)){
                        role = "";
                    }
                    //按组织操作
                    if (userRolesList.get(i).getOrgId().toString().equals(orgIdStr) &&
                            positionCode.contains(role)) {
                        if ("10061013".equals(userRolesList.get(i).getRole())) {
                            userRolesList.get(i).setRole(userRolesList.get(i).getRole() + ",10061019");
                            for (CodeVO vo : listcode) {
                                if ("10061019".equals(vo.getCodeId().toString())) {
                                    userRolesList.get(i).setPositionName(userRolesList.get(i).getPositionName() + "(" + vo.getCodeCnDesc() + ")");
                                }
                            }
                        } else if ("10061019".equals(userRolesList.get(i).getRole())) {
                            userRolesList.remove(i);
                            i--;
                        }
                    }
                }
                positionCode = positionCode.replace("10061019", "");
                list.get(x).put("positionCode", positionCode);
            }
        }
        if(!userRolesList.isEmpty()){
            for (UserRoleDTO urdto:userRolesList){
                if(StringUtils.isNullOrEmpty(urdto.getPositionName())){
                    urdto.setPositionName(urdto.getRoleName());
                    urdto.setRoleName(urdto.getOrgName());

                }
            }
        }
        userData.put("roles", userRolesList);
        return userData;
    }


    /**
     * 获取用户的权限数据
     *
     * @return Map
     * @author maxingjian
     * @date 2019年9月19日
     */
    @Override
    public List<UserRoleDTO> roleDetail() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<UserRoleDTO> empRoles = userLoginMapper.findEmpRoles(loginInfoDto.getUserId().toString());
        for (UserRoleDTO empRole : empRoles) {
            if (empRole.getRoleType() != null) {
                String[] split = empRole.getRoleType().split(",");
                HashSet<String> roleTypeSet = new HashSet<>();
                for (String s : split) {
                    roleTypeSet.add(s);
                }
                List<String> roleTypeList = new ArrayList<>();
                for (String aLong : roleTypeSet) {
                    roleTypeList.add(aLong);
                }
                Collections.sort(roleTypeList);

                String role = "";
                for (int i = 0; i < roleTypeList.size() - 1; i++) {
                    role = role + roleTypeList.get(i) + ",";
                }
                if (roleTypeList.size() > 0) {
                    role = role + roleTypeList.get(roleTypeList.size() - 1);
                }
                empRole.setRoleType(role);
                empRole.setRole(role);
            }

        }
        return empRoles;
    }



    /**
     * 获取用户的权限数据
     *
     * @return Map
     * @author wst
     * @date 2019年9月19日
     */
//    @Override
    public List<UserRoleDTO> roleDetailc() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<CodeVO> listcode = baseCommonCodeService.getCodeListByType(String.valueOf(ManageDictCodeConstants.CHECKEDLIST1));
//        Map<Integer,String> codeMap = listcode.stream().collect(Collectors.toMap(CodeVO::getCodeId, CodeVO::getCodeCnDesc));
        Map<Integer,String> codeMap2 = new HashMap<>();
        codeMap2.put(10061011,"前台接待");
        codeMap2.put(10061012,"网销顾问");
        codeMap2.put(10061013,"展厅经理");
        codeMap2.put(10061015,"展厅顾问");
        codeMap2.put(10061019,"网销经理");
        List<UserRoleDTO> empRoles = userLoginMapper.findEmpPotenialtRoles(loginInfoDto.getUserId().toString());
        List<UserRoleDTO> otherList = new ArrayList<>();

        UserRoleDTO empRoleNew = new UserRoleDTO();
        int empRoleIndex=0;
        int empRolesSize = empRoles.size();
        String codeStr = "";

        for (UserRoleDTO empRole : empRoles) {
            if (empRole.getRoleType() != null) {
                String[] split = empRole.getRoleType().split(",");
//                String[] splitName = empRole.getRoleName().split(",");
                HashSet<String> roleTypeSet = new HashSet<>();
                for (int i=0;i<split.length;i++) {
                    boolean isNum = split[i].matches("[0-9]+");
                    Integer sNum = 0;
                    if(isNum){
                        sNum = Integer.valueOf(split[i]);
                    }
                    if(ObjectUtils.isEmpty(codeMap2.get(sNum))){
                        if(codeStr.indexOf(split[i])<0){
                            UserRoleDTO empRoleOld = new UserRoleDTO();
                            if(StringUtils.isNullOrEmpty(empRoleNew.getDealerCode())){
                                BeanMapperUtil.copyProperties(empRole,empRoleNew);
                                empRoleNew.setRoleType(split[i]);
                                empRoleNew.setRole(split[i]);
//                             empRoleNew.setRoleName(splitName[i]);
                                codeStr += split[i]+",";

                            }else{
                                String roleTypeNew = empRoleNew.getRoleType()+","+split[i];
                                String roleNameNew = empRoleNew.getRoleName()+","+empRole.getRoleName();
                                empRoleNew.setRoleName(roleNameNew);
                                empRoleNew.setRoleType(roleTypeNew);
                                empRoleNew.setRole(roleTypeNew);
                                codeStr += split[i]+",";

                            }
                        }



                    }else{

                        if(codeStr.indexOf(split[i])<0){
                            UserRoleDTO empRoleOld = new UserRoleDTO();
                            if(StringUtils.isNullOrEmpty(empRoleOld.getDealerCode())){
                                BeanMapperUtil.copyProperties(empRole,empRoleOld);
                                empRoleOld.setRoleType(split[i]);
                                empRoleOld.setRole(split[i]);
                                otherList.add(empRoleOld);
                                codeStr += split[i]+",";
                            }
                        }

                    }
                }

            }
            if(empRoleIndex+1==empRolesSize&&!StringUtils.isNullOrEmpty(empRoleNew.getDealerCode())){
                //最后一次循环
                otherList.add(empRoleNew);
            }
            empRoleIndex++;
        }

        return otherList;
    }

    /**
     * 获取用户的权限数据
     *
     * @return Map
     * @author maxingjian
     * @date 2019年9月19日
     */
    @Override
    public List<UserRoleDTO> getDetailForPad() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return userLoginMapper.findEmpPotenialRolesForPad(loginInfoDto.getUserId().toString());
    }


    /**
     * jwt校验用户是否已经登录
     *
     * @return String
     * @author maxingjian
     * @date 2017年6月23日
     */
    @Override
    public String appAuthCas() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String userCode = null;
        if (null != loginInfo) {
            userCode = loginInfo.getUserCode();
        }
        return userCode;
    }

    @Override
    public Map<String, String> getLoginUser() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map loginUser = getLoginUser(loginInfoDto.getAppId(), loginInfoDto.getUserCode(), "true", "1");
        return loginUser;
    }

    @Override
    public String checkRole() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String role = loginInfoDto.getAppRole().toString();
        if (role.isEmpty()) {
            role = "0";
        }
        if (userLoginMapper.findUserRole(loginInfoDto.getEmployeeId().toString(), role) > 0) {
            return "1";
        } else {
            return "0";
        }
    }

    /**
     * 根据品牌id查询
     *
     * @param userId
     * @return com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto
     * @author renwd
     * @since 2018/11/27
     */
    @Override
    public LoginInfoDto getLoginInfoDto(String userId, String userAgent, boolean flag) {
        String messageFormat = MessageFormat.format(com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants.LOGIN_CACHE_USERID, userAgent);
        Object loginInfoDto = redisClient.hget(messageFormat, userId);
        String userIdL = userId;
        if (flag == true) {
            String[] userIds = userId.split("-");
            userIdL = userIds[1];
        }
        if (null == loginInfoDto) {
            // 查询所有数据
            LoginInfoDto dto = userLoginMapper.getLoginInfoDto(userIdL);
            if (dto != null) {
                dto.setLoginWay(userAgent);
                List<UserRoleDTO> userRolesList = userLoginMapper.findEmpRoles(dto.getUserId().toString());
                if (userRolesList.size() > 0) {
                    dto.setCompanyId(userRolesList.get(0).getCompanyId());
                    dto.setOrgId(userRolesList.get(0).getOrgId());
                    dto.setOrgName(userRolesList.get(0).getOrgName());
                    dto.setOwnerCode(userRolesList.get(0).getDealerCode());
                    dto.setOwnerParCode(userRolesList.get(0).getDealerCode());
                    dto.setDealerName(userRolesList.get(0).getDealerName());
                    dto.setOwnerId(userRolesList.get(0).getDealerId().toString());
                    dto.setCompanyCode(userRolesList.get(0).getCompanyCode());
                    dto.setOrgIds(userRolesList.get(0).getOrgIds());
                    dto.setDataType(userRolesList.get(0).getDataType());
                    dto.setUserOrgId(userRolesList.get(0).getUserOrgId());
                }
                loginInfoDto = dto;
                logger.info("查询用户Dto:{}", loginInfoDto);
                redisClient.hsetExpire(messageFormat, userId, JSONUtil.objectToJson(loginInfoDto), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
        }
        return loginInfoDto == null ? null : JSONUtil.jsonToObj(JSONUtil.objectToJson(loginInfoDto), LoginInfoDto.class);

    }

    /**
     * REDIS存ROLE
     *
     * @param role
     * @return String
     * @author 马邢健
     * @since 2019/02/27
     */
    @Override
    public String setRole(String role) {
        String messageFormat = BaseDataCommonConstants.USER_CACHE_ROLE;
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        redisClient.hsetExpire(messageFormat, loginInfoDto.getUserId().toString(), JSONUtil.objectToJson(role), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
        return role;
    }


    /**
     * REDIS存USERROLE
     *
     * @param userRoleDTO
     * @return String
     * @author 马邢健
     * @since 2019/09/16
     */
    @Override
    public String setUserRole(UserRoleDTO userRoleDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        loginInfoDto.setUserOrgId(userRoleDTO.getUserOrgId());
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.LOGIN_CACHE_USERID, loginInfoDto.getLoginWay());
        Object dto = redisClient.hget(messageFormat, loginInfoDto.getUserId().toString());
        LoginInfoDto loginInfoDtoQ = JSONUtil.jsonToObj(JSONUtil.objectToJson(dto), LoginInfoDto.class);
        if (userRoleDTO != null) {
            loginInfoDtoQ.setCompanyId(userRoleDTO.getCompanyId());
            loginInfoDtoQ.setOrgId(userRoleDTO.getOrgId());
            loginInfoDtoQ.setOrgName(userRoleDTO.getOrgName());
            loginInfoDtoQ.setOwnerCode(userRoleDTO.getDealerCode());
            loginInfoDtoQ.setDealerName(userRoleDTO.getDealerName());
            loginInfoDtoQ.setOwnerId(userRoleDTO.getDealerId().toString());
            loginInfoDtoQ.setCompanyCode(userRoleDTO.getCompanyCode());
            loginInfoDtoQ.setOrgIds(userRoleDTO.getOrgIds());
            loginInfoDtoQ.setDataType(userRoleDTO.getDataType());
            //暂不用了
            //cms 修改  切换角色时候 ，orgType 跟着变化
            loginInfoDtoQ.setOrgType(userRoleDTO.getOrgType());
            loginInfoDtoQ.setUserOrgId(userRoleDTO.getUserOrgId());
            redisClient.hsetExpire(messageFormat, loginInfoDto.getUserId().toString(), JSONUtil.objectToJson(loginInfoDtoQ), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
            operateLogService.recordLog(loginInfoDtoQ, String.valueOf(ManageDictCodeConstants.LOG_SYSTEM_MANAGEMENT), "", "");
            return userRoleDTO.getOrgName();
        }
        return "";
    }


    /**
     * REDIS存ROLE，swarrgger用
     *
     * @param role
     * @return String
     * @author 马邢健
     * @since 2019/03/12
     */
    @Override
    public String setRole(String role, String userId) {
        String messageFormat = BaseDataCommonConstants.USER_CACHE_ROLE;
        redisClient.hsetExpire(messageFormat, userId, JSONUtil.objectToJson(role), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
        return role;
    }

    /**
     * REDIS取ROLE
     *
     * @param
     * @return String
     * @author 马邢健
     * @since 2019/02/27
     */
    @Override
    public String getRole(String userId) {
        String messageFormat = "cyxdms:sysAuth:role";
        Object role = redisClient.hget(messageFormat, userId);
        if (null == role) {
            return null;
        }
        return JSONUtil.objectToJson(role);
    }

    /**
     * REDIS取ROLE
     *
     * @param
     * @return String
     * @author 马邢健
     * @since 2019/02/27
     */
    @Override
    public UserRoleDTO getUserRole(String userId) {
        String messageFormat = BaseDataCommonConstants.USER_CACHE_USER_ROLE;
        Object role = redisClient.hget(messageFormat, userId);
        if (null == role) {
            return null;
        }
        return JSONUtil.jsonToObj(JSONUtil.objectToJson(role), UserRoleDTO.class);
    }

    /**
     * REDIS取ROLE
     *
     * @param
     * @return String
     * @author 马邢健
     * @since 2019/02/27
     */
    @Override
    public UserRoleDTO getUserAllRole(String userId) {

        Object userRoleDTO = redisClient.hget(BaseDataCommonConstants.USER_CACHE_USER_ROLE, userId);
        if (null == userRoleDTO) {
            List<UserRoleDTO> userRolesList = userLoginMapper.findEmpPotenialRoles(userId);
            if (userRolesList.size() > 0) {
                redisClient.hsetExpire(BaseDataCommonConstants.USER_CACHE_USER_ROLE, userId, JSONUtil.objectToJson(userRolesList.get(0)), SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
                userRoleDTO = userRolesList.get(0);
            }
            if (userRoleDTO == null) {
                return null;
            }
        }
        return JSONUtil.jsonToObj(JSONUtil.objectToJson(userRoleDTO), UserRoleDTO.class);
    }


    /**
     * 取ROLE
     *
     * @param
     * @return String
     * @author 马邢健
     * @since 2019/02/27
     */
    @Override
    public Map<String, Object> getRoles(String userId) {
        Map<String, Object> map = userLoginMapper.queryRoleByEmpNo(userId);
        return map;
    }


    /**
     * TODO description
     *
     * @param username
     * @return
     * @author maxingjian
     * @date 2019-01-10
     */
    private List<Map> getUser(String appId, String username, String mobilePhone) {
        List<Map> user = userLoginMapper.getUser(appId, username, mobilePhone);
        return user;
    }

    /**
     * @description：
     * @author ：quankk
     * @date ：Created in 2019/5/20 17:03
     * @modified By：
     */
    private String verifyCheckCode(String appId, String userCode, String phone, String checkCode, String regId) {
        if (StringUtils.isNullOrEmpty(phone) || StringUtils.isNullOrEmpty(checkCode)) {
            throw new DMSAuthException("请传入手机号或验证码");
        }
        logger.info("绑定手机bindPhone（）接收参数phone：{},checkCode:{}", phone, checkCode);
        List<Map> listMap = userLoginMapper.logCheck(appId, userCode, null, null);
        if (!CommonUtils.isNullOrEmpty(listMap)) {
            Map userInfo = listMap.get(0);
            Map<String, Object> map = MapUtils.newHashMap();
/*            Long userId = (Integer) userInfo.get("empId");
            Date loginLastTime = (Date) userInfo.get("loginLastTime");// 上次登录时间
            String isOnJob = userInfo.get("isOnjob").toString();// 在职状态
            Integer userStatus = (Integer) userInfo.get("userStatus");
            String passwordMD5 = (String) userInfo.get("passWord");// 密码*/

            //comCheckCode(SysAuthCommonConstants.SEND_MSG_2, phone, checkCode);
            String code = (String) redisClient.get("cyxdms:login:" + appId + ":" + phone);
            if (!checkCode.equals(code)) {
                comCheckCode(SysAuthCommonConstants.SEND_MSG_2, phone, checkCode);
                //throw new DMSAuthException(994, "验证码错误");
                //return "false";
            }
            redisClient.del("cyxdms:login:" + appId + ":" + phone);
            // 更新tc_user，记录登录人员设备信息，一个账号，最后一个人的设备id有效
            if (!StringUtils.isNullOrEmpty(regId)) {
                updateRegId(appId, userCode, regId);
            }

            if (!CommonUtils.isNullOrEmpty(listMap) && listMap.size() > 1) {
                return "false";
            } else {
                return "true";
            }
        } else {
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("msg", "账号不存在");
            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, JSONUtil.objectToJson(map));
        }

    }

    /**
     * 验证用户名密码是否正确
     *
     * @param userCode
     * @param password
     * @param groupCode
     * @return
     * @author adu
     * @date 2019年8月19日
     */
    private Map<String, String> userlogCheck(String appId, String userCode, String password, String groupCode, String verificationCode, String deviceId, String regId) throws IOException {
        List<Map> listMap = userLoginMapper.logCheck(appId, userCode, password, groupCode);
        if (!CommonUtils.isNullOrEmpty(listMap)) {
            Map userInfo = listMap.get(0);

            Map<String, Object> map = MapUtils.newHashMap();
            Integer userId = Integer.parseInt(userInfo.get("userId").toString());
            Date loginLastTime = (Date) userInfo.get("loginLastTime");// 上次登录时间
            String isOnJob = userInfo.get("isOnjob").toString();// 在职状态
            Integer userStatus = Integer.parseInt(userInfo.get("userStatus").toString());
            UserPO userPO = userMapper.selectById(userId);
            userPO.setLoginLastTime(LocalDateTime.now());
            // 获取登录失败次数
            Object firstfail = userInfo.get("failureNum");
            String failureNum = "";
            if (StringUtils.isNullOrEmpty(firstfail)) {
                failureNum = "0";
            } else {
                failureNum = userInfo.get("failureNum").toString();
            }

            if (Integer.parseInt(isOnJob) == SysAuthDictCodeConstants.EMPLOYEE_NOJOB
                    || userStatus == SysAuthDictCodeConstants.STATUS_JY) {
                map.put("msg", SysAuthCommonConstants.USER_INVALID);
                throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_995, JSONUtil.objectToJson(map));
            }

            Integer failureNum1 = Integer.parseInt(failureNum) + 1;
            Integer failureNum2 = Integer.parseInt(failureNum) - 9;
            Integer failureNum3 = Integer.parseInt(failureNum) - 19;
            Integer failureNum4 = Integer.parseInt(failureNum) - 29;
            // 判断锁定状态
            Integer lockFlag = (Integer) userInfo.get("lockFlag");
            if (lockFlag == SysAuthDictCodeConstants.STATUS_IS_YES) {
                if (Integer.parseInt(failureNum) == 20) {
                    map.put("msg", SysAuthCommonConstants.LOGIN_LOCK);
                    throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, JSONUtil.objectToJson(map));
                } else {
                    Date now = Calendar.getInstance().getTime();
                    double nowtime = now.getTime();
                    double logintime = loginLastTime.getTime();
                    double timeDifference = Math.floor(nowtime / 160000 - logintime / 160000);
                    double timeDifference2 = Math.floor(30 - timeDifference);
                    NumberFormat nf = NumberFormat.getInstance();
                    String timeDifference3 = nf.format(timeDifference2);
                    if (timeDifference < 1) {
                        map.put("msg", "当前账户被锁定，请" + timeDifference3 + "分钟后重试！");
                        //throw new ServiceBizException(JSONUtil.objectToJson(map));
                        throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, JSONUtil.objectToJson(map));
                    } else {
                        // 5分钟时间到，解锁
                    }
                }
            }
            // 第20次输错密码

            logger.debug("用户经销商------------:" + (String) userInfo.get("ownerCode"));

            logger.debug("用户是否首次登陆------------:" + StringUtils.isNullOrEmpty(loginLastTime));
            int isFirstLogin = StringUtils.isNullOrEmpty(loginLastTime) || StringUtils.isEquals(password, "gacne@2019") ? SysAuthDictCodeConstants.STATUS_IS_YES : SysAuthDictCodeConstants.STATUS_IS_NOT;
            // 更新tc_user，记录登录人员设备信息，一个账号，最后一个人的设备id有效
            if (!StringUtils.isNullOrEmpty(regId)) {
                updateRegId(appId, userCode, regId);
            }

            Map<String, String> result = MapUtils.newHashMap();
            result.put("isFirstLogin", String.valueOf(isFirstLogin));

            result.put("userId", String.valueOf(userInfo.get("userId")));
            //   result.put("EMPLOYEE_NO", String.valueOf(userInfo.get("employeeId")));
            result.put("employeeId", String.valueOf(userInfo.get("employeeId")));
            result.put("orgCode", String.valueOf(userInfo.get("orgCode")));
            result.put("userCode", String.valueOf(userInfo.get("userCode")));
            result.put("userStatus", String.valueOf(userInfo.get("userStatus")));
            if (!CommonUtils.isNullOrEmpty(listMap) && listMap.size() > 1) {
                result.put("isfalse", "false");
            } else {
                result.put("isfalse", "true");
            }
            return result;
        } else {
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("msg", "账号不存在");
            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, JSONUtil.objectToJson(map));
        }
    }

    /**
     * 更新设备信息
     *
     * @param userCode
     * @param regId
     * @return void
     * @author renwd
     * @since 2019/3/21
     */
    private void updateRegId(String appId, String userCode, String regId) {
        userMapper.updateByRegId(regId);
        //可切换变成按照主键更新
//        QueryWrapper<UserPO> wrapper = new QueryWrapper<>();
//        wrapper.lambda().eq(UserPO::getRegId, regId);
//        List<UserPO> userPOList = userMapper.selectList(wrapper);
//        for(UserPO po : userPOList){
//            po.setRegId(null);
//            userMapper.updateById(po);
//        }

        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserPO::getUserCode, userCode).eq(UserPO::getAppId, appId);
        UserPO userPO = userMapper.selectOne(queryWrapper);
        userPO.setRegId(regId);
        userMapper.updateById(userPO);
    }


    /**
     * 生成验证码
     *
     * @param map
     * @return void
     * @author renwd
     * @since 2019/3/6
     */
    private void generateCode(String appId, Map<String, Object> map, String userCode, String deviceId) throws IOException {
        Map<String, Object> generate = Verification.generate();
        String randomNum = String.valueOf(generate.get("random"));

        // 将随机数放入redis 账号+随机数/设备id+随机数
        String messageFormat = MessageFormat.format(SysAuthCommonConstants.VERIFICATION_CODE, appId);
        redisClient.hsetExpire(messageFormat, userCode, randomNum, SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
        redisClient.hsetExpire(messageFormat, deviceId, randomNum, SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);

        BufferedImage bi = (BufferedImage) generate.get("bufferedImage");
        map.put("verificationCode", Verification.getStream(bi));
    }


    /**
     * 校验验证码是否正确
     *
     * @param userCode
     * @param verificationCode
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author renwd
     * @since 2019/3/6
     */
    private Map<String, Object> checkVerificationCode(String appId, String userCode, String deviceId, String verificationCode) throws IOException {
        Map<String, Object> map = MapUtils.newHashMap();

        // 根据账号校验验证码
        String messageFormat = MessageFormat.format(SysAuthCommonConstants.VERIFICATION_CODE, appId);
        Object accountRandomNum = redisClient.hget(messageFormat, userCode);
        if (StringUtils.isEqualsNoCasetive(accountRandomNum, verificationCode)) {
            redisClient.hdel(messageFormat, userCode);
            redisClient.hdel(messageFormat, deviceId);
            return null;
        }

        // 根据设备校验验证码
        Object deviceRandomNum = redisClient.hget(messageFormat, deviceId);
        if (StringUtils.isEqualsNoCasetive(deviceRandomNum, verificationCode)) {
            redisClient.hdel(messageFormat, userCode);
            redisClient.hdel(messageFormat, deviceId);
            return null;
        }

        // 都不相同返回错误
        generateCode(appId, map, userCode, deviceId);
        map.put("msg", "验证码失效或输入错误");
        throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE, JSONUtil.objectToJson(map));
    }

    /**
     * 刷新验证码
     *
     * @param username
     * @param deviceId
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author renwd
     * @since 2019/3/7
     */
    @Override
    public Map<String, Object> refreshVerification(String appId, String username, String deviceId) throws IOException {
        Map<String, Object> newMap = MapUtils.newHashMap();
        generateCode(appId, newMap, username, deviceId);
        return newMap;
    }

    /**
     * 校验输错几次，并修改错误次数
     *
     * @param userId      id
     * @param validation
     * @param failureNum
     * @param failureNums
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author renwd
     * @since 2019/3/5
     */
    private void getStringStringMap(Integer userId, boolean validation, String failureNum, Integer failureNums, Map map) {
        if (validation == false) {
            setEmpPo(Integer.parseInt(failureNum), userId);
            map.put("msg", "密码错误，密码已经输错" + failureNums + "次，输错10次账号将被锁定");
            //throw new ServiceBizException(JSONUtil.objectToJson(map));
            throw new DMSAuthException((failureNums > 2 ? SysAuthCommonConstants.ERROR_CODE : SysAuthCommonConstants.OT_CODE), JSONUtil.objectToJson(map));
        } else {
            setEmpPo2(userId);
        }
    }

    /**
     * 密码输错，失败次数加1
     *
     * @param userId
     * @param num
     * @return
     * @author gaojian
     */
    private UserPO setEmpPo(int num, int userId) {
        UserPO userPO = userMapper.selectById(userId);
        userPO.setFailureNum(num + 1);
        if (userPO.getFailureNum() > 4) {
            userPO.setLockCause("登录冻结");
        }
        userMapper.updateById(userPO);
        return userPO;
    }

    /**
     * 密码正确，失败次数清0
     *
     * @param userId
     * @return
     * @author gaojian
     */
    public UserPO setEmpPo2(int userId) {
        UserPO userPO = userMapper.selectById(userId);
        userPO.setFailureNum(0);
        userMapper.updateById(userPO);
        return userPO;
    }

    /**
     * 插入登录时间
     *
     * @param userId
     * @return
     * @author gaojian
     */
    private UserPO setEmpPo3(int userId) {
        UserPO userPO = userMapper.selectById(userId);
        userPO.setLoginLastTime(LocalDateTime.now());
        userMapper.updateById(userPO);
        return userPO;
    }

    /**
     * 锁定账户
     *
     * @param userId
     * @return
     * @author gaojian
     */
    private void setEmpPo4(int userId) {
        UserPO userPO = userMapper.selectById(userId);
        userPO.setLockFlag(SysAuthDictCodeConstants.STATUS_IS_YES);
        userMapper.updateById(userPO);
    }

    /**
     * 密码正确，失败次数清0,解锁
     *
     * @param userId
     * @return
     * @author gaojian
     */
    public UserPO setEmpPo6(int userId, String appId) {
        UserPO userPO = userMapper.selectById(userId);
        userPO.setFailureNum(0);
        userPO.setLockFlag(ManageDictCodeConstants.NO_IS_LOCK);
        userPO.setLockCause(null);
        userMapper.updateById(userPO);
        // 根据账号校验验证码
        String messageFormat = MessageFormat.format(SysAuthCommonConstants.VERIFICATION_CODE, appId);
        redisClient.hdel(messageFormat, userPO.getUserCode());
        redisClient.hdel(messageFormat, "app");
        redisClient.hdel(messageFormat, "pc");
        return userPO;
    }

    /**
     * TODO description
     *
     * @param appId userCode
     * @return
     * @author maxingjian
     * @date 2018年12月18日
     */

    public Map getLoginUser(String appId, String userCode, String falseFlag, String userType) {
        List<Map> listMap = userLoginMapper.getLoginUser(appId, userCode);
        if (!listMap.isEmpty()) {
            listMap.get(0).put("kickOut", true);
            listMap.get(0).put("userType", userType);
            listMap.get(0).put("isfalse", falseFlag);
            listMap.get(0).put("employeeDutyType", 4);
        }
        return listMap.get(0);
    }

    /**
     * 解锁账户
     *
     * @param userId
     * @return
     * @author gaojian
     */
    private void setEmpPo5(int userId) {
        UserPO userPO = userMapper.selectById(userId);
        userPO.setLockFlag(SysAuthDictCodeConstants.STATUS_IS_NOT);
        userMapper.updateById(userPO);
    }

    /**
     * @description：
     * @author ：quankk
     * @date ：Created in 2019/2/28 15:00
     * @modified By：
     */
    @Override
    public EmployeeDTO emp(String appId, String employeeNo) {
        return empMapper.selectByEmployeeNo(appId, employeeNo);
    }

    /**
     * @description：修改密码
     * @author ：quankk
     * @date ：Created in 2019/3/4 15:05
     * @modified By：
     */
    @Override
    public String updatePassword(PasswordDTO passwordDTO) throws Exception {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.info("修改密码loginInfoDto.getUserAccount()：....{}", loginInfoDto.getUserCode());
        logger.info("原密码oldPassword：....{}", passwordDTO.getOldPassword());
        logger.info("新密码newPassword：....{}", passwordDTO.getNewPassword());
        LambdaQueryWrapper<UserPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(UserPO::getUserCode, loginInfoDto.getUserCode()).eq(UserPO::getAppId, loginInfoDto.getAppId());
        UserPO userPo = userMapper.selectOne(queryWrapper);
        String oldPasswordMD5 = userPo.getPassword();
        //效验原密码是否正确
        RSAUtils rsaUtils = new RSAUtils();
        RSAPrivateKey privateKey = rsaUtils.getprivateKey();
        String oldPassword = rsaUtils.decryptToString(passwordDTO.getOldPassword(), privateKey);
        boolean validation = MD5Util.validPassword(oldPassword, oldPasswordMD5);
        if (validation == false) {
            throw new ServiceBizException("原密码填写错误！");
        }
        //效验新密码与原密码是否一样
        String newPassword = rsaUtils.decryptToString(passwordDTO.getNewPassword(), privateKey);
        boolean newValidation = MD5Util.validPassword(newPassword, oldPasswordMD5);
        if (newValidation == true) {
            throw new ServiceBizException("新密码与原密码一致！");
        }
        userPo.setPassword(MD5Util.getEncryptedPwd(newPassword));
        userPo.setUpdatePasswordDate(LocalDateTime.now());
        userMapper.updateById(userPo);
        return "";
    }

    /**
     * @description：退出
     * @author ：quankk
     * @date ：Created in 2019/3/5 11:30
     * @modified By：
     */
    @Override
    public String logout(String jwt, Long userLoginId) {
        // 更新tc_user，将设备id更新为null
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if (!StringUtils.isNullOrEmpty(loginInfoDto.getLoginWay()) && loginInfoDto.getLoginWay().equals(String.valueOf(SysAuthDictCodeConstants.STATUS_IS_NOT))) {
            QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(UserPO::getUserCode, loginInfoDto.getUserCode()).eq(UserPO::getAppId, loginInfoDto.getAppId());
            UserPO userPO = userMapper.selectOne(queryWrapper);
            userPO.setUpdatedAt(LocalDateTime.now());
            userPO.setRegId(null);
            userMapper.updateById(userPO);
        }
        if (userLoginId != null) {
            TtUserLoginPO ttUserLoginPO = ttUserLoginMapper.selectById(userLoginId);
            ttUserLoginPO.setLastOperateDate(LocalDateTime.now());
            ttUserLoginPO.setLogOutDate(LocalDateTime.now());
            ttUserLoginMapper.updateById(ttUserLoginPO);
        }

        //删除logininfodto
        logger.debug("删除redis登录对象路径：{}，登录方式：{}", BaseDataCommonConstants.LOGIN_CACHE_USERID, loginInfoDto.getLoginWay());
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.LOGIN_CACHE_USERID, loginInfoDto.getLoginWay());
        redisClient.hdel(messageFormat, loginInfoDto.getUserId().toString());
        jwtService.delJwtWithJwt(jwt);
        //调用智慧通推送 JWT
        RestResultResponse rlt = new RestResultResponse();
        Map<String, Object> headeParams = new HashMap<>();
        headeParams.put("jwt",jwt);
        //远程调用对象：url / body参数（json）/ header / bizId
        MessEvent messEvent = new MessEvent();
        messEvent.setParam(headeParams);    // 请求头
        messEvent.setUrl("http://OPS-NOTIFY/notify/invoke/message?channel=zhtLogout");
        messEvent.setHeaders(new HashMap<>());
        iRemoteInvoke.sendPostWithTransaction(messEvent);
        return "1";
    }

    /**
     * @description：查询当前版本号
     * @author ：quankk
     * @date ：Created in 2019/3/5 16:54
     * @modified By：
     */
    @Override
    public Map<String, String> appVersionNo(String appType, String appId) {
        String messageFormat = BaseDataCommonConstants.VERSION_CACHE_TYPE;
        Object appVersionDto = redisClient.hget(messageFormat, appType + appId);
        if (null == appVersionDto) {
            // 查询所有数据
            LambdaQueryWrapper<AppVersionPO> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(AppVersionPO::getAppType, appType).eq(AppVersionPO::getAppId, appId).eq(AppVersionPO::getStatus, SysAuthDictCodeConstants.STATUS_IS_VALID);
            AppVersionPO appVersionPO = appVersionMapper.selectPage(new Page<>(1, 1), queryWrapper).getRecords().get(0);
            ;
            logger.info("查询用户Dto:{}", appVersionPO);
            if (null == appVersionPO) {
                return null;
            }
            AppVersionDto dto = new AppVersionDto();
            BeanUtils.copyProperties(appVersionPO, dto);
            redisClient.hsetExpire(messageFormat, appType + appId, JSONUtil.objectToJson(dto), SysAuthCommonConstants.EXPIRE_TIME_ONE_HOUR);
            appVersionDto = dto;
        }
        AppVersionDto appVersionDtoQ = JSONUtil.jsonToObj(JSONUtil.objectToJson(appVersionDto), AppVersionDto.class);
        Map map = new HashMap();
        map.put("versionNo", appVersionDtoQ.getVersionNo());
        map.put("remark", appVersionDtoQ.getRemark());
        map.put("url", appVersionDtoQ.getUrl());
        map.put("appId", appVersionDtoQ.getAppId());
        return map;//.getVersionNo();
    }

    /**
     * @description：
     * @author ：quankk
     * @date ：Created in 2019/3/7 15:37
     * @modified By：
     */
    @Override
    public List<UserDTO> userByCondition(UserDTO userDTO) {
        return userMapper.userByCondition(userDTO);
    }

    /**
     * @description：
     * @author ：quankk
     * @date ：Created in 2019/3/12 14:25
     * @modified By：
     */
    @Override
    public String updateAppVersion(String appType, String appVersion, String appId) {
        LambdaQueryWrapper<AppVersionPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(AppVersionPO::getAppType, appType).eq(AppVersionPO::getAppId, appId).eq(AppVersionPO::getStatus, SysAuthDictCodeConstants.STATUS_IS_VALID);
        AppVersionPO appVersionPO = appVersionMapper.selectPage(new Page<>(1, 1), queryWrapper).getRecords().get(0);
        appVersionPO.setVersionNo(appVersion);
        appVersionMapper.update(appVersionPO, queryWrapper);

        String messageFormat = BaseDataCommonConstants.VERSION_CACHE_TYPE;
        redisClient.hdel(messageFormat, appType + appId);

        AppVersionDto dto = new AppVersionDto();
        BeanUtils.copyProperties(appVersionPO, dto);
        redisClient.hsetExpire(messageFormat, appType + appId, JSONUtil.objectToJson(dto), SysAuthCommonConstants.EXPIRE_TIME_ONE_HOUR);

        return "";
    }

    /**
     * @description：消息推送
     * @author ：quankk
     * @date ：Created in 2019/4/19 14:34
     * @modified By：
     */
    @Override
    public String pushByUserIdOrEmpNo(PushDTO pushDTO) {
        //根据userId查询设备ID
        logger.debug("消息推送开始:{}", pushDTO.toMaps());
        String regId = userLoginMapper.selectRegIdByUserId(pushDTO.getUserId(), "");//pushDTO.getEmployeeNo());
        if (StringUtils.isNullOrEmpty(regId)) {
            logger.debug("消息未推送regId不存在");
            throw new DMSAuthException("消息未推送regId不存在");
        }
        List<String> targetCodes = new ArrayList<String>();
        targetCodes.add(regId);
        JPushDTO jPushDTO = new JPushDTO();
        BeanUtils.copyProperties(pushDTO, jPushDTO);
        jPushDTO.setTargetCodes(targetCodes);
        ExtDTO extDTO = new ExtDTO();
        Map<String, Object> platform = new HashMap<String, Object>();
        platform.put("platformSpecific", "");
        extDTO.setPlatform(platform);
        extDTO.setBusiness(pushDTO.getExtra());
        jPushDTO.setExt(extDTO);
        logger.info("查询到的pushAppId：{}", pushDTO.getUserId());
        String result = pushService.apps(jPushDTO, ApplicationContextHelper.getBeanByType(LoginInfoDto.class).getAppId());
        addTzMsg(jPushDTO, pushDTO);
        logger.info("推送消息返回result：{}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String resultCode = jsonObject.getString("code");
        logger.info("返回状态码：" + resultCode);
        if (!"200".equals(resultCode)) {
            String message = jsonObject.getString("error");
            logger.info("返回结果：" + message);
            throw new DMSAuthException(message);
        }
        return result;
    }

    @Override
    public String pushbyuseridtozht(PushDTO pushDTO, String jwt) {
        return null;
    }

    private JSONObject pushZHT(String url,Map headParams,Map map,String message){
        JSONObject data = null;
        RestServiceRequestDto requestDto = new RestServiceRequestDto();
        if(headParams != null){
            requestDto.setHeadersParams(headParams);
        }
        requestDto.setUrl(url);
        requestDto.setBody(map);
        logger.info("CMS-智慧通"+message+"接口URL:{},header参数;{},请求参数body:{}", url,JSON.toJSONString(headParams==null?"":headParams),JSON.toJSONString(map));
        RestServiceResponseDto request = httpService.postJsonRequest(requestDto);
        logger.info("CMS-智慧通"+message+"接口请求结果:{}", JSON.toJSONString(request));
        userLoginMapper.insertZhtLog(JSONObject.toJSONString(requestDto),JSONObject.toJSONString(request));
        if (request.getResultCode() == RestServiceResponseDto.SUCCESS) {
            try {
                JSONObject jsonResponse = JSONObject.parseObject(request.getResponseMsg());
                if (jsonResponse == null || jsonResponse.isEmpty() || !jsonResponse.containsKey("code")
                        || jsonResponse.getInteger("code") != 200 || !jsonResponse.containsKey("data")) {
                    throw new ServiceBizException(
                            jsonResponse != null && !jsonResponse.isEmpty() && jsonResponse.containsKey("errMsg")
                                    ? jsonResponse.getString("errMsg")
                                    : message+"接口请求异常");
                }
                data = jsonResponse.getJSONObject("data");
            }catch (Exception e) {
                throw new ServiceBizException(message+"接口请求异常");
            }
        } else {
            throw new ServiceBizException(message+"接口请求异常");
        }
        return data;
    }

    @Override
    public void pushMsg(PushMsgDTO pushDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        new Thread(() -> {
            List<String> targetCodes = new ArrayList<>();
            List<String> list = pushDTO.getUsers();
            String regId = null;
            if (list.size() > 0) {
                regId = userLoginMapper.selectRegIdByUserIds(list);
                logger.debug("推送的用户regId：{} " + regId);
            }
            //极光推送
            try {
                if (!StringUtils.isNullOrEmpty(regId)) {
                    String[] regIds = regId.split(",");
                    if (!StringUtils.isNullOrEmpty(regIds)) {
                        for (String rId : regIds) {
                            targetCodes.add(rId);
                        }
                    }
                    JPushDTO jPushDTO = new JPushDTO();
                    org.springframework.beans.BeanUtils.copyProperties(pushDTO, jPushDTO);
                    jPushDTO.setTargetCodes(targetCodes);
                    ExtDTO extDTO = new ExtDTO();
                    Map<String, Object> platform = new HashMap<String, Object>();
                    platform.put("platformSpecific", "");
                    extDTO.setPlatform(platform);
                    extDTO.setBusiness(pushDTO.getExtra());
                    jPushDTO.setExt(extDTO);
                    logger.debug("极光的jPushDTO：{}" + jPushDTO.toString());
                    pushService.apps(jPushDTO, loginInfoDto.getAppId());
                }
            } catch (Exception e) {
                logger.debug("调用极光异常，但是被捕获:{}", e);
            }

            //融云IM
            try {
                if (!StringUtils.isNullOrEmpty(tmUrl)) {
                    TextNotifyDto textNotifyDto = new TextNotifyDto();
                    ExtraImDto extraImDto = new ExtraImDto();
                    textNotifyDto.setAppId(loginInfoDto.getAppId());
                    textNotifyDto.setPlatform("Tencent");
                    textNotifyDto.setContent(pushDTO.getContent());
                    extraImDto.setTitle(pushDTO.getTitle());
                    extraImDto.setContent(pushDTO.getContent());
                    extraImDto.setPushType("TZ");
                    textNotifyDto.setExtra(extraImDto);
                    textNotifyDto.setToUsers(list);
                    logger.debug("开始调用TM:{}", textNotifyDto.toString());
                    pushIm(textNotifyDto);
                }
            } catch (Exception e) {
                logger.debug("调用TM异常，但是被捕获:{}", e);
            }
        }).start();
    }

    public String pushIm(TextNotifyDto textNotifyDto) {
        RestServiceRequestDto restServiceRequestDto = new RestServiceRequestDto();
        Map<String, String> headersParams = new HashMap<>();
        headersParams.put("appId", textNotifyDto.getAppId());
        restServiceRequestDto.setUrl(tmUrl);
        restServiceRequestDto.setHeadersParams(headersParams);
        restServiceRequestDto.setBody(textNotifyDto);
        RestServiceResponseDto restServiceResponseDto = httpRequestService.postJsonRequest(restServiceRequestDto);
        return restServiceResponseDto.getResponseMsg();
    }

    /**
     * 推送消息保存到数据库
     */
    public void addTzMsg(JPushDTO jPushDto, PushDTO pushDTO) {
        //获取登陆信息
        MsgRecordPO mesRecordDto = new MsgRecordPO();
        mesRecordDto.setAppId(pushDTO.getExtra().getExtend1());
        //   mesRecordDto.setMsgType(((ExtDTO) jPushDto.getExt()).getBusiness().getTemplateCode());
        mesRecordDto.setMsgType(((ExtDTO) jPushDto.getExt()).getBusiness().getTzType());
        mesRecordDto.setUserId(pushDTO.getUserId());
        mesRecordDto.setMsgCode(SysAuthCommonConstants.NOTICE_TZ);
        mesRecordDto.setMsgContent(jPushDto.getContent());
        mesRecordDto.setMsgTitle(jPushDto.getTitle());
        mesRecordDto.setTemplateCode(((ExtDTO) jPushDto.getExt()).getBusiness().getTemplateCode());
        mesRecordDto.setMsgSender(String.valueOf(pushDTO.getUserId()));
        mesRecordDto.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_NO);
        Long dateLong = ((ExtDTO) jPushDto.getExt()).getBusiness().getDateTime();
        mesRecordDto.setCreatedAt(new DateTime(dateLong));
        //  mesRecordDto.setMsgReceiver(null);
        msgRecordMapper.addTzMsg(mesRecordDto);

        logger.info("推送消息：》" + mesRecordDto.toString());
    }

    /**
     * @description：短信验证码发送
     * @author ：quankk
     * @date ：Created in 2019/5/15 18:07
     * @modified By：
     */
    @Override
    public SendSmsResultDTO sendSms(Short smsType, String phone) throws Exception {
        int ifBinding = ifBinding(phone);
        if (smsType == SysAuthCommonConstants.SEND_MSG_2
                || smsType == SysAuthCommonConstants.SEND_MSG_3
                || smsType == SysAuthCommonConstants.SEND_MSG_4) {
            if (ifBinding == 0) {
                throw new DMSAuthException(800,SysAuthCommonConstants.PHONE_NOT_BINDING);
            }
        }
        logger.info("验证码发送smsType:{},手机号phone:{}", smsType, phone);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String app = loginInfoDto.getAppId();
        String checkCode = "";
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            int ch = new Random().nextInt(10);
            sb.append(ch);
        }
        checkCode = sb.toString();
        logger.info("生成的验证码为：{}", checkCode);
        // 短信参数
        Map<String,Object> params = new HashMap<>();
        params.put("code",checkCode);
        SendSmsResultDTO sendSmsResultDTO =  new SendSmsResultDTO();
        SendSmsResponse sendSmsResponse =  sendSms(accessKeyId,accessKeySecret,phone,signName,templateCode,JSON.toJSONString(params));
        logger.info("短信发送返回结果：{}", sendSmsResponse);
        String message = "";
        if (sendSmsResponse != null){
            String code = sendSmsResponse.getBody().getCode();
            if ("OK".equals(code)){
                sendSmsResultDTO.setIfSuccess(true);
            }else {
                sendSmsResultDTO.setIfSuccess(false);
            }
            message = JSON.toJSONString(sendSmsResponse.getBody());
        }
        //if (!isSame) {
        SmsLogPO smsLogPO = new SmsLogPO();
        smsLogPO.setMobile(phone);
        smsLogPO.setCheckCode(checkCode);
        smsLogPO.setContent(checkCode);
        smsLogPO.setSmsType(BigDecimal.valueOf(smsType));
        smsLogPO.setErrorCount(0);
        smsLogPO.setMinute(Integer.valueOf(minute));
        smsLogPO.setReturnMessage(message);
        smsLogPO.setAppId(app);
        smsLogMapper.insert(smsLogPO);
        sendSmsResultDTO.setCheckCode(checkCode);
        sendSmsResultDTO.setIfBinding(ifBinding);
        return sendSmsResultDTO;
    }

    /**
     * @description：手机号是否绑定
     * @author ：quankk
     * @date ：Created in 2019/5/17 15:38
     * @modified By：
     */
    public int ifBinding(String phone) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.info("校验的手机号为，{}", phone);
        LambdaQueryWrapper<EmpPo> empPoLambdaQueryWrapper = new QueryWrapper().lambda();
        empPoLambdaQueryWrapper.eq(EmpPo::getMobilePhone, phone).eq(EmpPo::getAppId, loginInfoDto.getAppId());
        List<EmpPo> empPoList = empMapper.selectList(empPoLambdaQueryWrapper);
        if (CommonUtils.isNullOrEmpty(empPoList)) {
            return 0;
        }
        if (empPoList.size() > 1){
            throw new DMSAuthException(800,SysAuthCommonConstants.PHONE_NOT_ERROR);
        }
        return 1;
    }

    /**
     * @description：绑定手机号码
     * @author ：quankk
     * @date ：Created in 2019/5/17 16:17
     * @modified By：
     */
    @Override
    public String bindPhone(BindPhoneDTO bindPhoneDTO) {
        comCheckCode(SysAuthCommonConstants.SEND_MSG_1, bindPhoneDTO.getPhone(), bindPhoneDTO.getCheckCode());
        //查询是否存在绑定
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        EmpPo empPoRecord = empMapper.selectById(loginInfoDto.getEmpId());
        if (!StringUtils.isNullOrEmpty(empPoRecord.getMobilePhone())) {
            if (empPoRecord.getMobilePhone().equals(bindPhoneDTO.getPhone())) {
                throw new DMSAuthException("该手机号已被该用户绑定");
            }
        }
        LambdaQueryWrapper<EmpPo> empPoLambdaQueryWrapper = new QueryWrapper().lambda();
        empPoLambdaQueryWrapper.eq(EmpPo::getMobilePhone, bindPhoneDTO.getPhone()).eq(EmpPo::getAppId, loginInfoDto.getAppId());
        List<EmpPo> empPoList = empMapper.selectList(empPoLambdaQueryWrapper);
        if (!CommonUtils.isNullOrEmpty(empPoList)) {
            EmpPo empPo = empPoList.get(0);
            empPo.setIsReplace(1);
            empPo.setMobilePhone(null);
            empMapper.updateById(empPo);

            //查询jwt踢出用户
            LambdaQueryWrapper<UserPO> userPOLambdaQueryWrapper = new QueryWrapper().lambda();
            userPOLambdaQueryWrapper.eq(UserPO::getUserCode, empPo.getUserCode()).eq(UserPO::getAppId, loginInfoDto.getAppId());
            UserPO userPO = userMapper.selectOne(userPOLambdaQueryWrapper);
            // Object jwt = redisClient.get(userPO.getUserId().toString());
            // Object pcjwt= userPO.getUserId().toString()+SysAuthCommonConstants.JWT_CLIENT_DELIMITER+SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_PC;
            //  logger.info("查询jwt踢出用户{}", jwt);
            if (jwtService.delJwtInfo(userPO.getUserId().toString())) {
                userPO.setUpdatedAt(LocalDateTime.now());
                userPO.setRegId(null);
                userMapper.updateById(userPO);
            }
        }

        empPoRecord.setMobilePhone(bindPhoneDTO.getPhone());
        empMapper.updateById(empPoRecord);
        return "";
    }

    /**
     * @description：更新校验错误次数
     * @author ：quankk
     * @date ：Created in 2019/5/17 19:11
     * @modified By：
     */
    private void updateErrorCount(SmsLogPO smsLogPO) {
        smsLogPO.setErrorCount(smsLogPO.getErrorCount() + 1);
        smsLogPO.setLastCheckTime(LocalDateTime.now());
        smsLogMapper.updateById(smsLogPO);
    }

    /**
     * @author ：quankk
     * @date ：2019/5/21 16:31
     * @description：校验手机号验证码
     */
    @Override
    public String verifyCheckCode(BindPhoneDTO bindPhoneDTO) {
        List<Integer> employeeIds = userLoginMapper.selectEmployeeIdByPhone(bindPhoneDTO.getAppId(), bindPhoneDTO.getPhone());
        if (StringUtils.isNullOrEmpty(employeeIds)) {
            throw new DMSAuthException(800,SysAuthCommonConstants.PHONE_NOT_BINDING);
        }
        if (employeeIds.size() > 1 ) {
            throw new DMSAuthException(800,SysAuthCommonConstants.PHONE_NOT_ERROR);
        }
        comCheckCode(bindPhoneDTO.getSmsType(), bindPhoneDTO.getPhone(), bindPhoneDTO.getCheckCode());
        if (bindPhoneDTO.getSmsType().intValue() == SysAuthCommonConstants.SEND_MSG_4) {
            logger.info("接收的openId:{}", bindPhoneDTO.getOpenId());
//            EmployeePO employeePO = employeeMapper.selectById(employeeId);
//            if (StringUtils.isNullOrEmpty(employeePO.getEmployeeName())) {
//                employeePO.setEmployeeName(bindPhoneDTO.getNickname());
//            }
//            employeeMapper.updateById(employeePO);

            LambdaQueryWrapper<EmpPo> empPoLambdaQueryWrapper = new QueryWrapper().lambda();
            empPoLambdaQueryWrapper.eq(EmpPo::getMobilePhone, bindPhoneDTO.getPhone()).eq(EmpPo::getAppId, bindPhoneDTO.getAppId());
            List<EmpPo> empPoList = empMapper.selectList(empPoLambdaQueryWrapper);
            if (!CommonUtils.isNullOrEmpty(empPoList)) {
                EmpPo empPo = empPoList.get(0);
                giveEmpParams(empPo, bindPhoneDTO);
                if (StringUtils.isNullOrEmpty(empPo.getEmployeeName())) {
                    empPo.setEmployeeName(bindPhoneDTO.getNickname());
                }
                empMapper.updateById(empPo);

            }
        }
        return "";
    }

    private void giveEmpParams(EmpPo empPo, BindPhoneDTO bindPhoneDTO) {
        empPo.setOpenId(bindPhoneDTO.getOpenId());
        empPo.setWechat(bindPhoneDTO.getNickname());
        if (!StringUtils.isNullOrEmpty(bindPhoneDTO.getOpenId())) {
            if (StringUtils.isNullOrEmpty(empPo.getHeadPortrait())) {
                empPo.setHeadPortrait(bindPhoneDTO.getHeadPortrait());
            }
            if (StringUtils.isNullOrEmpty(empPo.getEmployeeName())) {
                empPo.setEmployeeName(bindPhoneDTO.getNickname());
            }
            empPo.setWechat(bindPhoneDTO.getNickname());
            if (StringUtils.isNullOrEmpty(empPo.getAddress())) {
                String address = (StringUtils.isNullOrEmpty(bindPhoneDTO.getCountry()) ? "" : bindPhoneDTO.getCountry())
                        + (StringUtils.isNullOrEmpty(bindPhoneDTO.getProvince()) ? "" : bindPhoneDTO.getProvince())
                        + (StringUtils.isNullOrEmpty(bindPhoneDTO.getCity()) ? "" : bindPhoneDTO.getCity());
                empPo.setAddress(address);
            }
        } else {
            empPo.setWechat(null);
        }
    }

    public void comCheckCode(Short smsType, String phone, String checkCode) {
        logger.info("绑定手机bindPhone（）接收参数phone：{},checkCode:{}", phone, checkCode);
        LambdaQueryWrapper<SmsLogPO> smsLogPOLambdaQueryWrapper = new QueryWrapper<SmsLogPO>().lambda();
        smsLogPOLambdaQueryWrapper.eq(SmsLogPO::getMobile, phone).orderByDesc(SmsLogPO::getId).last(" LIMIT 1");
//        smsLogPOLambdaQueryWrapper.eq(SmsLogPO::getMobile, phone).eq(SmsLogPO::getSmsType, smsType).orderByDesc(SmsLogPO::getId).last(" LIMIT 1");
        SmsLogPO smsLogPO = smsLogMapper.selectOne(smsLogPOLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(smsLogPO)) {
            throw new DMSAuthException(994, "验证码错误");
        }
        if (!checkCode.equals(smsLogPO.getCheckCode())) {
            updateErrorCount(smsLogPO);
            throw new DMSAuthException(994, "验证码错误");
        }
        if (smsLogPO.getCreatedAt().plusMinutes(SysAuthCommonConstants.SMS_CHECK_TIME).isBefore(LocalDateTime.now())) {
            updateErrorCount(smsLogPO);
            throw new DMSAuthException(994, "验证码错误");
        }
        LocalDateTime dateTime = smsLogPO.getCreatedAt().plusMinutes(smsLogPO.getMinute());
        if (!LocalDateTime.now().isBefore(dateTime)){
            throw new DMSAuthException(800, "验证码已超时");
        }
    }

    /**
     * @author ：quankk
     * @date ：2019/5/21 17:32
     * @description：忘记密码修改密码
     */
    @Override
    public String forgetUpdatePassword(PasswordDTO passwordDTO) throws Exception {
        comCheckCode(SysAuthCommonConstants.SEND_MSG_3, passwordDTO.getPhone(), passwordDTO.getCheckCode());
        //查询是否存在绑定
        LambdaQueryWrapper<EmpPo> empPoLambdaQueryWrapper = new QueryWrapper().lambda();
        empPoLambdaQueryWrapper.eq(EmpPo::getMobilePhone, passwordDTO.getPhone()).eq(EmpPo::getAppId, passwordDTO.getAppId());
        List<EmpPo> empPoList = empMapper.selectList(empPoLambdaQueryWrapper);
        RSAUtils rsaUtils = new RSAUtils();
        RSAPrivateKey privateKey = rsaUtils.getprivateKey();
        String newPassword = rsaUtils.decryptToString(passwordDTO.getNewPassword(), privateKey);
        EmpPo empPo = empPoList.get(0);
        Long empId = empPo.getEmpId();
        QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
        userPOQueryWrapper.eq("app_id", passwordDTO.getAppId()).eq("emp_id", empId);
        UserPO userPO = userMapper.selectOne(userPOQueryWrapper);
        userPO.setPassword(MD5Util.getEncryptedPwd(newPassword));
        userMapper.updateById(userPO);
        return "";
    }

    /**
     * @author ：quankk
     * @date ：2019/5/22 11:57
     * @description：微信绑定，修改，解绑
     */
    @Override
    public String bindWeChart(BindPhoneDTO bindPhoneDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.info("++++++++++++++++++++++++++++++appId:" + loginInfoDto.getAppId());
        logger.info("++++++++++++++++++++++++++++++loginInfoDto:" + loginInfoDto.toString());
        EmpPo empPo = empMapper.selectById(loginInfoDto.getEmpId());
        giveEmpParams(empPo, bindPhoneDTO);
        empMapper.updateById(empPo);
        return "";
    }

    /**
     * @author ：quankkBrokerServiceImpl:492
     * @date ：2019/5/22 15:31
     * @description：个人信息
     */
    @Override
    public EmpInfoDTO empInfo() {
        logger.info("++++++++++++++++++++++++++++++进入了:");
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        EmpInfoDTO result = userLoginMapper.empInfo(loginInfoDto.getUserId(), "", loginInfoDto.getAppId());
        logger.info("++++++++++++++++++++++++++++++进入了:{}", JSONUtil.objectToJson(result));
        String str = "";
        if (!StringUtils.isNullOrEmpty(result.getProvinceId())) {
            RegionVO vo = baseCommonRegionService.dataByRegionId(result.getProvinceId());
            if (vo != null) {
                str += vo.getRegionName();
            }
        }
        if (!StringUtils.isNullOrEmpty(result.getCityId())) {
            RegionVO vo = baseCommonRegionService.dataByRegionId(result.getCityId());
            if (vo != null) {
                str += vo.getRegionName();
            }
        }
        if (!StringUtils.isNullOrEmpty(result.getCountyId())) {
            RegionVO vo = baseCommonRegionService.dataByRegionId(result.getCountyId());
            if (vo != null) {
                str += vo.getRegionName();
            }
        }
        //获取经销商
        DealerAttachVO dealerAttachVO = cmsChannelCommonService.getDealerInfoByDealerCode(loginInfoDto.getOwnerCode());
        // 容错，避免前台展示null
        if(!ObjectUtils.isEmpty(dealerAttachVO)){
            // 容错，避免前台展示null
            result.setAddress(str + (StringUtils.isNullOrEmpty(dealerAttachVO.getSalesAddress()) ? "" : dealerAttachVO.getSalesAddress()));
        }
        return result;
    }

    /**
     * @author ：quankk
     * @date ：2019/5/22 16:05
     * @description：修改保存个人信息
     */
    @Override
    public String updateEmpInfo(EmpInfoDTO empInfoDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        EmpPo empPo = empMapper.selectById(loginInfoDto.getEmpId());
        if (!StringUtils.isNullOrEmpty(empInfoDTO.getHeadPortrait())) {
            empPo.setHeadPortrait(empInfoDTO.getHeadPortrait());
        }
        if (!StringUtils.isNullOrEmpty(empInfoDTO.getRoleName())) {
            empPo.setRoleName(empInfoDTO.getRoleName());
        }
        empMapper.updateById(empPo);
//        logger.debug("名片更新到im_表数据开始");
//        LambdaQueryWrapper<UserPO> userPOLambdaQueryWrapper = new QueryWrapper().lambda();
//        userPOLambdaQueryWrapper.eq(UserPO::getEmpId, empPo.getEmpId());
//        userPOLambdaQueryWrapper.eq(UserPO::getAppId, empPo.getAppId());
//        UserPO userPO = userMapper.selectOne(userPOLambdaQueryWrapper);
//        logger.debug("名片更新到im_表数据---userPO:{}", userPO);
//        UserInfoDTO userInfoDTO = new UserInfoDTO();
//        userInfoDTO.setUserId(Long.parseLong(String.valueOf(userPO.getUserId())));
//        userInfoDTO.setAppId(userPO.getAppId());
//        userInfoDTO.setUserToken(userPO.getUserId().toString());
//        userInfoDTO.setUserName(empPo.getEmployeeName());
//        userInfoDTO.setIsStop(0);
//        // userInfoDTO.setDealerCode(employeePO.getOwnerCode());
//        // 用户头像
//        userInfoDTO.setUserPic(empPo.getHeadPortrait());
//        userInfoDTO.setPhone(empPo.getMobilePhone());
//        userInfoDTO.setUserCode(userPO.getUserCode());
//        // fixme 把用户信息同步到im
//        imService.saveOrUpdate(userInfoDTO);
//        logger.debug("人员信息同步到IM完成");
        return "";
    }

    /**
     * @author ：quankk
     * @date ：2019/7/8 15:28
     * @description：根据查询条件返回对应的用户数据 PC迁移
     */
    @Override
    public Map<String, Object> initUserData() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.info("打印登录信息。。。。。。。。。。。。。。" + loginInfoDto);
        logger.info("打印登录信息。。。。。。。。。。。。。。" + loginInfoDto.getUserId());
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("dataType", "10461003");
        returnMap.put("employeeNo", "RL2190");
        //员工职责类型
        returnMap.put("employeeDutyType", this.getEmployeeDutyType("RL", loginInfoDto.getEmployeeNo()));
        return returnMap;
    }

    private int getEmployeeDutyType(String appId, String employeeNo) {
        //0：获取失败 1销售顾问 2电销顾问 3展厅接待 4销售经理 5不是指定角色
        int reuslt = 0;
        try {
            if (this.isConsultant(appId, employeeNo)) {
                reuslt = 1;
            } else if (this.isTeleConsultant(appId, employeeNo)) {
                reuslt = 2;
            } else if (this.isSalesManager(appId, employeeNo)) {
                reuslt = 4;
            } else {
                reuslt = 3;
            }
        } catch (Exception e) {
            logger.error("获取失败", e);

        }
        return reuslt;
    }

    /**
     * 临时使用:是否为销售顾问
     */
    private boolean isConsultant(String appId, String employeeNo) throws Exception {
        Map map = userLoginMapper.isConsultant(appId, employeeNo);
        return null == map ? false : true;
    }

    /**
     * 临时使用:是否为销售顾问
     */
    private boolean isTeleConsultant(String appId, String employeeNo) throws Exception {
        Map map = userLoginMapper.isTeleConsultant(appId, employeeNo);
        return null == map ? false : true;
    }

    /**
     * 临时使用:是否为销售顾问
     */
    private boolean isSalesManager(String appId, String employeeNo) throws Exception {
        Map map = userLoginMapper.isSalesManager(appId, employeeNo);
        return null == map ? false : true;
    }

    /**
     * @author ：quankk
     * @date ：2019/8/19 16:21
     * @description：加载用户的菜单 PC迁移
     */
    @Override
    public List<MenuVueDto> getMenus() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        loginInfo.setUserId(1503L);
        loginInfo.setCompanyId(1L);
        loginInfo.setAppId("RL");
        loginInfo.setUserOrgId(1521L);
        loginInfo.setDataType(10461003L);
        loginInfo.setUserCode("yangjie");
        Long userId = loginInfo.getUserId();
        Integer orgType = loginInfo.getDataType().intValue();
        String userAccount = loginInfo.getUserCode();
        List<Map> menus;
        if (SysAuthDictCodeConstants.DATA_TYPE_BY_GROUP == orgType) {
            menus = menuMapper.queryMenu(orgType, loginInfo.getAppId(), loginInfo.getUserOrgId(), userAccount, SysAuthDictCodeConstants.BILL_TYPE_PERMISSION_USER, SysAuthDictCodeConstants.DATA_TYPE_BY_GROUP);
        } else {
            if (SysAuthDictCodeConstants.DATA_TYPE_BY_OWNER == orgType) {
                menus = menuMapper.queryMenu(orgType, loginInfo.getAppId(), loginInfo.getUserOrgId(), userAccount, SysAuthDictCodeConstants.BILL_TYPE_PERMISSION_USER, SysAuthDictCodeConstants.DATA_TYPE_BY_OWNER);
            } else {
                menus = menuMapper.queryMenu(orgType, loginInfo.getAppId(), loginInfo.getUserOrgId(), userAccount, SysAuthDictCodeConstants.BILL_TYPE_PERMISSION_USER, SysAuthDictCodeConstants.DATA_TYPE_BY_SUPER);
            }
        }
        Map<String, MenuVueDto> childMap = new LinkedHashMap<String, MenuVueDto>();
        List<MenuVueDto> menuMap = new ArrayList<MenuVueDto>();

        List<UserPermissionActionListDTO> list = userMapper.getUserPermissionAction(loginInfo.getUserOrgId(), ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER);

        for (int i = 0; i < menus.size(); i++) {
            String type = menus.get(i).get("MENU_TYPE").toString();
            MenuVueDto menuDto = new MenuVueDto();
            menuDto.setPath((String) menus.get(i).get("MENU_NAME_ZH").toString());
            if (menus.get(i).get("PYT") != null) {
                menuDto.setPyt((String) menus.get(i).get("PYT").toString());
            } else {
                menuDto.setPyt("");
            }
//            if (menus.get(i).get("PERMISSION") != null) {
//                menuDto.setPermission((String) menus.get(i).get("PERMISSION").toString());
//            } else {
//                menuDto.setPermission("");
//            }
            menuDto.setId((String) menus.get(i).get("MENU_ID").toString());
            menuDto.setName((String) menus.get(i).get("MENU_NAME_EN"));
            menuDto.setIsFavorite(menus.get(i).get("FAVORITE").toString());
            MenuMetaVueDto metaVueDto = new MenuMetaVueDto();
            if (menus.get(i).get("MENU_ICON") != null) {
                metaVueDto.setIcon((String) menus.get(i).get("MENU_ICON").toString());
            }
            menuDto.setTitle(menus.get(i).get("MENU_NAME").toString());//暂无DAOUtil.getLocaleFieldValue(menus.get(i), "MENU_NAME"));
            metaVueDto.setTitle(menus.get(i).get("MENU_NAME").toString());//暂无DAOUtil.getLocaleFieldValue(menus.get(i), "MENU_NAME"));
            menuDto.setMeta(metaVueDto);
            String url = "system/pageError.html";
            if (menus.get(i).get("MENU_URL") != null) {
                url = (String) menus.get(i).get("MENU_URL").toString();
            }
            menuDto.setComponent(url);
            String parentId = (String) menus.get(i).get("PARENT_ID").toString();
            menuDto.setParentId(parentId);

//            List<UserPermissionActionListDTO> list = userMapper.getUserPermissionAction(loginInfo.getUserOrgId(), ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER);

            if ("1001".equals(type)) {
                menuDto.setChildren(new ArrayList<MenuVueDto>());
                menuDto.setKey((String) menus.get(i).get("MENU_NAME_ZH").toString());
                menuMap.add(menuDto);
            }
            if ("1002".equals(type)) {
                MenuVueDto parentMenu = getParentMenuVueById(menuMap, parentId);
                menuDto.setKey((String) menus.get(i).get("MENU_NAME_ZH").toString());
                menuDto.setChildren(new ArrayList<MenuVueDto>());
                childMap.put(menuDto.getId(), menuDto);
                if (parentMenu != null) {
                    parentMenu.getChildren().add(menuDto);
                }
            }
            if ("1003".equals(type)) {
                MenuVueDto parentMenu = childMap.get(parentId);
                menuDto.setKey("/" + (String) menus.get(i).get("MENU_URL").toString());
                Map<String, List<UserPermissionActionListDTO>> map = new HashMap<>();
                List listUrl = new ArrayList<>();
                for (UserPermissionActionListDTO userPermissionActionListDTO : list) {
                    if (userPermissionActionListDTO.getMenuId().equals(menuDto.getId())) {
                        listUrl.add(userPermissionActionListDTO.getActionCode());
                    }
                }
                menuDto.setPermission(listUrl);
                if (parentMenu != null) {
                    parentMenu.getChildren().add(menuDto);
                }
            }
        }
        return menuMap;
    }


    /**
     * @author ：quankk
     * @date ：2019/8/19 16:21
     * @description：加载用户的菜单 PC迁移
     */
    @Override
    public List<MenuVueDto> getFavoriteMenus() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<Map> menus = menuMapper.getFavoriteMenus(loginInfo.getUserOrgId());
        List<MenuVueDto> menuMap = new ArrayList<MenuVueDto>();
        for (int i = 0; i < menus.size(); i++) {
            String type = menus.get(i).get("MENU_TYPE").toString();
            MenuVueDto menuDto = new MenuVueDto();
            menuDto.setPath((String) menus.get(i).get("MENU_NAME_ZH").toString());
            if (menus.get(i).get("PYT") != null) {
                menuDto.setPyt((String) menus.get(i).get("PYT").toString());
            } else {
                menuDto.setPyt("");
            }
            menuDto.setId((String) menus.get(i).get("MENU_ID").toString());
            menuDto.setName((String) menus.get(i).get("MENU_NAME_EN"));
            menuDto.setIsFavorite(menus.get(i).get("FAVORITE").toString());
            MenuMetaVueDto metaVueDto = new MenuMetaVueDto();
            if (menus.get(i).get("MENU_ICON") != null) {
                metaVueDto.setIcon((String) menus.get(i).get("MENU_ICON").toString());
            }
            menuDto.setTitle(DAOUtil.getLocaleFieldValue(menus.get(i), "MENU_NAME"));
            metaVueDto.setTitle(DAOUtil.getLocaleFieldValue(menus.get(i), "MENU_NAME"));
            menuDto.setMeta(metaVueDto);
            String url = "system/pageError.html";
            if (menus.get(i).get("MENU_URL") != null) {
                url = (String) menus.get(i).get("MENU_URL").toString();
            }
            menuDto.setComponent(url);
            menuMap.add(menuDto);
        }
        return menuMap;
    }

    private MenuVueDto getParentMenuVueById(List<MenuVueDto> parentMenus, String menuId) {
        if (!CommonUtils.isNullOrEmpty(parentMenus)) {
            for (MenuVueDto menu : parentMenus) {
                if (menu.getId().equals(menuId)) {
                    return menu;
                }
            }
        }
        return null;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/8 17:17
     * @description：*查询用户操作功能
     */
    @Override
    public List<Map> handles() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long userId = loginInfo.getUserId();
        if (SysAuthDictCodeConstants.DATA_TYPE_BY_OWNER == loginInfo.getDataType()) {
            List<Map> result = userLoginMapper.queryHandles(loginInfo.getCompanyId(), userId);
            for (int i = 0; i < result.size(); i++) {
                String handle = (String) result.get(i).get("code");
                handle = handle.replaceAll("\\{[^/]+\\}", "\\\\d+");
                result.get(i).put("code", handle + "$");
            }
            return result;
        } else {
            List<Map> result = userLoginMapper.handles(loginInfo.getAppId(), userId);
            for (int i = 0; i < result.size(); i++) {
                String handle = (String) result.get(i).get("code");
                handle = handle.replaceAll("\\{[^/]+\\}", "\\\\d+");
                result.get(i).put("code", handle + "$");
            }
            return result;
        }
    }

    @Override
    public void verificationCode(String phone, String appId, Integer bindingPhone) {
        if (bindingPhone == null) {
            bindingPhone = 0;
        }
        Integer count = empMapper.findCountByPhoneAndAppId(phone, appId);
        if (count == 0 && bindingPhone == 1) {
            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, "该账号未绑定");
        } else if (count > 1 && bindingPhone == 1) {
            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, "手机号绑定账号过多，请联系管理员");
        }
        wechatScanLoginService.sendSms(phone, appId);
    }

    @Override
    @Transactional
    public void bindingPhone(BindingPhoneVO bindingPhoneVO) {
        String phone = bindingPhoneVO.getPhone();
        String appId = bindingPhoneVO.getAppId();
        Integer confirm = bindingPhoneVO.getConfirm();
        String username = bindingPhoneVO.getUsername();
        EmpPo empPo = empMapper.queryEmpByCode(username, appId);
        if (confirm == 0) {
            String code = (String) redisClient.get("cyxdms:login:" + appId + ":" + phone);
            String checkCode = bindingPhoneVO.getCheckCode();
            if (!checkCode.equals(code)) {
                throw new DMSAuthException(996, "验证码输入错误");
            }
            Integer count = empMapper.findCountByPhoneAndAppIdAndEmpId(phone, appId, empPo.getEmpId());
            if (count > 0) {
                throw new DMSAuthException(995, "当前手机号绑定账号过多");
            }
        } else {
            empMapper.updatePhoneByPhone(phone, appId);
        }
        empPo.setMobilePhone(phone);
        empMapper.updateById(empPo);
    }

    /**
     * 用户绑定手机号
     *
     * @author ：李贺
     * @date ：2019/12/5
     */
    @Override
    public SmsWxVo getSmsWx(String appId) {
        Long factoryId = companyMapper.findFactoryIdByAppId(appId);
        SmsWxVo smsWxVo = companyMapper.getSmsWx(factoryId);
        if (smsWxVo == null) {
            smsWxVo = new SmsWxVo();
        }
        if (smsWxVo.getSmsType() == null) {
            smsWxVo.setSmsType(10041001);
        }
        if (smsWxVo.getWechatType() == null) {
            smsWxVo.setWechatType(10041001);
        }
        smsWxVo.setSpeech(10041001);
        smsWxVo.setUploadPhotos(10041001);

        List<Map<String, String>> systemParamPOS = systemParamMapper.findFactoryParam(companyMapper.findFactoryIdByAppId(appId), null);
        if (!CollectionUtils.isEmpty(systemParamPOS)) {
            for (Map<String, String> systemParamPO : systemParamPOS) {
                String paramCode = systemParamPO.get("paramCode");
                if (!StringUtils.isNullOrEmpty(paramCode)) {
                    if (paramCode.equals("speech")) {
                        String paramValue = systemParamPO.get("paramValue");
                        if (!StringUtils.isNullOrEmpty(paramValue) && paramValue.equals("10041002")) {
                            smsWxVo.setSpeech(10041002);
                        }
                    } else if (paramCode.equals("uploadPhotos")) {
                        String paramValue = systemParamPO.get("paramValue");
                        if (!StringUtils.isNullOrEmpty(paramValue) && paramValue.equals("10041002")) {
                            smsWxVo.setUploadPhotos(10041002);
                        }
                    }
                }
            }
        }
        return smsWxVo;
    }

    /**
     * 获得头像
     *
     * @author ：李贺
     * @date ：2019/12/5
     */
    @Override
    public String getHeadPortrait() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return empMapper.getHeadPortrait(loginInfoDto.getEmpId());
    }

    @Override
    public Map getUserInfoByToken(String token) {
        return null;
    }

    /**
     * 阿里云发送短信
     * @param accessKeyId
     * @param accessKeySecret
     * @param phone  手机号
     * @param singName 短信签名
     * @param templateCode 模板
     * @param templateParam  参数 {"code":"1111"}
     * @return
     * @throws Exception
     */
    public static SendSmsResponse sendSms(String accessKeyId , String accessKeySecret, String phone, String singName,String templateCode ,String templateParam) throws Exception {
        SendSmsResponse response = new SendSmsResponse();
        com.aliyun.dysmsapi20170525.Client client = createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(singName)
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);
        // 复制代码运行请自行打印 API 的返回值
        response = client.sendSms(sendSmsRequest);
        return response;
    }


    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

//    public static void main(String[] args) throws Exception {
//        SendSmsResponse response = new SendSmsResponse();
//        Integer minute = 5;
//
//        // 短信参数
//        Map<String,Object> params = new HashMap<>();
//        params.put("code","123456");
//        response =  sendSms("LTAI5tH6NyYWGKqDB6FFd5dp","oXb0kGr8UmLkh92NScQki2dl9JcmTC","15754326944","北汽营销","SMS_232825176",JSON.toJSONString(params));
//        System.out.println(JSON.toJSONString(response));
//    }
}
